// 导入数据库操作模块
const db = require('../db/index')
const uploadAvatar = require('../multer/upload')


// 获取全部商品的处理函数
exports.getAllGoods = (req, res) => {
    const sql = `select * from ev_goods`
    // 调用db.query()执行SQL语句
    db.query(sql, (err, results) => {
        // 执行SQL语句失败 
        if (err) return res.cc(err)
        // const totalPages = Math.ceil(results.length / req.body.pageSize)
        const start = req.body.pageNo * req.body.pageSize - req.body.pageSize
        const end = req.body.pageNo * req.body.pageSize
        const goodsList = results.slice(start, end)
        //商品获取成功
        res.send({
            code: 200,
            message: '获取商品数据成功',
            data: {
                goodsList,
                total: results.length,
            }
        })
    })
}

// 获取搜索商品的处理函数
exports.getGoodsList = (req, res) => {
    const search = req.body.keyword;
    const categoryName = req.body.categoryName;
    if (categoryName) {
        const sql = `select g.* from ev_goods as g left outer join ev_category as c on g.categoryId=c.categoryId where  g.isSale=1 and (g.goods_name like "%${search}%" or g.goods_title like "%${search}%" or g.goods_contents like "%${search}%") and  c.categoryName = ? `
        // 调用db.query()执行SQL语句
        db.query(sql, categoryName, (err, results) => {
            // 执行SQL语句失败 
            if (err) return res.cc(err)
            const totalPages = Math.ceil(results.length / req.body.pageSize)
            const start = req.body.pageNo * req.body.pageSize - req.body.pageSize
            const end = req.body.pageNo * req.body.pageSize
            const goodsList = results.slice(start, end)
            //商品获取成功
            res.send({
                code: 200,
                message: '获取搜索商品数据成功',
                data: {
                    goodsList,
                    pageSize: req.body.pageSize,
                    pageNo: req.body.pageNo,
                    totalPages,
                    total: results.length,
                    tes: results
                }
            })
        })
    } else {
        const sql = `select g.* from ev_goods as g left outer join ev_category as c on g.categoryId=c.categoryId where  g.isSale=1 and (g.goods_name like "%${search}%" or g.goods_title like "%${search}%" or g.goods_contents like "%${search}%")  `
        // 调用db.query()执行SQL语句
        db.query(sql, (err, results) => {
            // 执行SQL语句失败 
            if (err) return res.cc(err)
            const totalPages = Math.ceil(results.length / req.body.pageSize)
            const start = req.body.pageNo * req.body.pageSize - req.body.pageSize
            const end = req.body.pageNo * req.body.pageSize
            const goodsList = results.slice(start, end)
            //商品获取成功
            res.send({
                code: 200,
                message: '获取搜索商品数据成功',
                data: {
                    goodsList,
                    pageSize: req.body.pageSize,
                    pageNo: req.body.pageNo,
                    totalPages,
                    total: results.length,
                    res: results
                }
            })
        })
    }


}
// 根据商品分类获取商品的处理函数
exports.getGoodsListByCategory = (req, res) => {
    let idList = req.body
    const sql = `select * from ev_goods  where categoryId in  (${idList})`
    // 调用db.query()执行SQL语句
    db.query(sql, (err, results) => {
        res.send({
            code: 200,
            message: '商品获取成功',
            data: results
        })
    })
}

// 根据id获取商品详情的处理函数
exports.getGoodsDetail = (req, res) => {
    //  定义根据id查询商品详细信息的SQL语句
    const sql = 'select * from ev_goods where goods_id=?'
    // 调用db.query()执行SQL语句
    db.query(sql, req.params.id, (err, results) => {
        // 执行SQL语句失败
        if (err) return res.cc(err)
        // SQL 语句执行成功，但是没有查询到任何数据
        if (results.length !== 1) return res.cc('商品详情获取失败！')
        let goodsDetail = results[0];
        //商品详情获取成功
        //  定义根据id查询商品图片的SQL语句
        const sql2 = 'select * from ev_goodspic where goods_id=?'
        // 调用db.query()执行SQL语句
        db.query(sql2, req.params.id, (err, results) => {
            // 执行SQL语句失败
            if (err) return res.cc(err)
            // SQL 语句执行成功，但是没有查询到任何数据
            goodsDetail["imgList"] = results || []
            goodsDetail.imgList.unshift({ 'img_url': goodsDetail.goods_img })
            //商品详情获取成功
            res.send({
                code: 200,
                message: '商品详情获取成功',
                data: goodsDetail
            })
        })
    })
    // const sql = 'select g.*,p.img_url from ev_goods as g left outer join ev_goodspic as p on g.goods_id=p.goods_id where g.goods_id=?'

}
//上架商品的处理函数
exports.saleGoods = (req, res) => {
    const sql = 'update ev_goods set isSale=1 where goods_id=?'
    // 调用db.query()执行SQL语句
    db.query(sql, req.body.id, (err, results) => {
        // 执行SQL语句失败
        if (err) return res.cc(err)
        res.send({
            code: 200,
            message: '商品销售状态修改成功',
        })
    })
}
//下架商品的处理函数
exports.cancelGoods = (req, res) => {
    const sql = 'update ev_goods set isSale=0  where goods_id=?'
    // 调用db.query()执行SQL语句
    db.query(sql, req.body.id, (err, results) => {
        // 执行SQL语句失败
        if (err) return res.cc(err)
        res.send({
            code: 200,
            message: '商品销售状态修改成功',
        })
    })
}

//根据id获取（处理过）商品信息的处理函数
exports.getGoodsById = (req, res) => {
    //  定义根据id查询商品详细信息的SQL语句
    const sql = 'select goods_id,goods_name,goods_title,goods_contents,goods_price,categoryId,goods_img from ev_goods where goods_id=?'
    // 调用db.query()执行SQL语句
    db.query(sql, req.params.id, (err, results) => {
        // 执行SQL语句失败
        if (err) return res.cc(err)
        // SQL 语句执行成功，但是没有查询到任何数据
        if (results.length !== 1) return res.cc('商品详情获取失败！')
        let goodsDetail = results[0];
        //商品详情获取成功
        //  定义根据id查询商品图片的SQL语句
        const sql2 = 'select img_url from ev_goodspic where goods_id=?'
        // 调用db.query()执行SQL语句
        db.query(sql2, req.params.id, (err, results) => {
            // 执行SQL语句失败
            if (err) return res.cc(err)
            // SQL 语句执行成功，但是没有查询到任何数据
            // goodsDetail["imgList"] = results || []
            // goodsDetail.imgList.unshift({'img_url':goodsDetail.goods_img})
            let arr = []
            arr.push({ 'goods_img': goodsDetail.goods_img })
            results.forEach(item => {
                arr.push({ 'goods_img': item.img_url })
            });
            goodsDetail.goodsImageList = arr
            delete goodsDetail.goods_img

            //商品详情获取成功
            res.send({
                code: 200,
                message: '商品详情获取成功',
                data: goodsDetail,
            })
        })
    })
    // const sql = 'select g.*,p.img_url from ev_goods as g left outer join ev_goodspic as p on g.goods_id=p.goods_id where g.goods_id=?'

}

//删除商品的处理函数
exports.deleteGoods = (req, res) => {
    // 调用db.query()执行SQL语句
    if (req.params.id > 28) {
        const sql1 = 'delete from ev_goodspic where goods_id=?'
        db.query(sql1, req.params.id, (err, results) => { })
        const sql2 = 'delete from ev_cart where goods_id=?'
        db.query(sql2, req.params.id, (err, results) => { })
        const sql3 = 'delete from ev_order where goods_id=?'
        db.query(sql3, req.params.id, (err, results) => { })
        const sql4 = 'delete from  ev_goods  where goods_id=?'
        db.query(sql4, req.params.id, (err, results) => {
            // 执行SQL语句失败
            if (err) return res.cc(err)
            if (results.affectedRows < 1) return res.cc('删除失败！')
            res.send({
                code: 200,
                message: '商品删除成功',
            })
        })
    } else {
        res.send({
            code: 201,
            message: '商品删除失败',
        })
    }
}
// 添加商品的处理函数
exports.addGoods = (req, res) => {
    let goods_img = req.body.goodsImageList[0]
    let picList = req.body.goodsImageList.slice(1, req.body.goodsImageList.length)
    let obj = req.body
    obj.goods_img = goods_img.goods_img
    delete obj.goodsImageList
    const sql = 'insert into ev_goods set ?'
    db.query(sql, obj, (err, results) => {
        let id = results.insertId
        if (err) return res.cc(err)
        if (picList.length !== 0) {
            picList.forEach(item => {
                let obj2 = {}
                obj2.img_url = item.goods_img
                obj2.goods_id = id
                const sql2 = 'insert into ev_goodspic  set ?'
                db.query(sql2, obj2, (err, results2) => {
                })
            });
        }
        res.send({
            code: 200,
            message: '上传成功！',
            data: obj, picList, id
        })
    })
}
// 更新商品的处理函数
exports.updateGoods = (req, res) => {
    let goods_img = req.body.goodsImageList[0]
    let picList = req.body.goodsImageList.slice(1, req.body.goodsImageList.length)
    let obj = req.body
    obj.goods_img = goods_img.goods_img
    delete obj.goodsImageList
    const sql = 'update ev_goods set ? where goods_id=?'
    db.query(sql, [obj, req.body.goods_id], (err, results) => {
        if (err) return res.cc(err)
        if (picList.length !== 0) {
            const sql2 = 'delete from ev_goodspic  where goods_id=? '
            db.query(sql2, req.body.goods_id, (err, results2) => { })
            picList.forEach(item => {
                let obj2 = {}
                obj2.img_url = item.goods_img
                obj2.goods_id = req.body.goods_id
                console.log(obj2);
                const sql3 = 'insert into ev_goodspic set ? '
                db.query(sql3, obj2, (err, results3) => {

                })
            });

        }
        res.send({
            code: 200,
            message: '更新成功！',
            data: picList
        })
    })
}

// 上传图片的处理函数
exports.uploadImg = async (req, res) => {
    try {
        // 头像上传
        const uploadRes = await uploadAvatar(req, res)
        console.log(uploadRes);
        res.send({
            code: 200,
            data: uploadRes
        })
    } catch (error) {
        res.send(error)
    }
}





